<?php

namespace backend\controllers;

use bc\controller\BackendController;
use bc\model\knowledge\CategoryModel;
use bc\model\knowledge\KnowledgeModel;
use bc\model\knowledge\TagModel;
use bc\model\knowledge\TeacherModel;
use bc\model\knowledge\RelationModel;
use bc\model\knowledge\StatisticsModel;
use bc\util\backend\Page;
use bc\util\Uploader;


class  KnowledgeController extends BackendController
{
    public function  actionIndex()
    {
        $model = new KnowledgeModel();
		
		$params = '1 = 1';
	
		$title = $this->get('title');
                $type  = $this->get('type');
		if($title)
		{
			$params .= ' AND title LIKE "%' . $title . '%"'; 
		}
                if(isset($type))
                {
                        $params .=' AND bc_knowledge.type = '.$type;
                }
                
                $params .=' and bc_knowledge.status = 1';
                
		$page = $this->get('page', 1);

                $model->sort = 't_sort Desc';
		$list = $model->getBackendList($params, $page, self::PAGE_SIZE);
		
		$total = $model->getTotal($params);
		
		$pagination = new Page($total, self::PAGE_SIZE);
		
		$view['list'] = $list;
		$view['pagination'] = $pagination;
		$view['title'] = $title;
                $view['type'] = $type;
		
		return $this->render('index', $view);
    }
    
    public function actionAdd()
	{       
                $type  = $this->get('type');
		$teacherModel = new TeacherModel();
	        $teachers = $teacherModel->getList(['teacher_status'=>1]);
		
                $categoryModel = new CategoryModel();
                $categorys = $categoryModel->getList(['parent_id' => 0, 'cate_status' => 1]);
		                          
                $view['teachers'] = $teachers;
                $view['categorys'] = $categorys;
                $view['type'] = $type;
		
		return $this->render('add', $view);
	}
    
    public function  actionSave()
        {
                if($this->getRequest()->getMethod() === 'POST')
                {
                        $model = new KnowledgeModel();
                        $id = $this->post('id', 0);
                        
                        $data['title'] = $this->post('title', '');
			$data['teacher_id'] = $this->post('teacher_id', '');
                        $data['content'] = $this->post('content','');
                        $data['type'] = $this->post('type','');
                        //图片上传
                        //var_dump($_FILES['image']);die();
                        if($_FILES['image']['error'] != 4)
			{       
				$up = new Uploader( 'image' , $this->getUploadConfig() );
				$info = $up->getFileInfo();
				if($info['state'] === 'SUCCESS')
				{
					$data['image'] = str_replace(UPLOAD_PATH, '', $info['url']);
				}
					
                        }else{ 
                            
                                $teacherModel = new TeacherModel();
                                $teacher = $teacherModel->getRow(['teacher_id'=>$data['teacher_id'],'teacher_status'=>1]);
                                $data['image'] = $teacher['teacher_image'];
                        }
                        
                        $data['category_id'] = $this->post('category_id','');
                                               
                        $data['link'] = $this->post('link','');
                        $data['start_time'] = $this->post('start_time','');
                        $data['end_time'] = $this->post('end_time','');
                        $data['is_top'] = $this->post('is_top','');
                        $data['t_sort'] = $this->post('t_sort','');
                        
                        if(empty($data['is_top'])){
                            $data['t_sort'] = 0;
                        }else{
                            $data['t_sort'] = $this->post('t_sort','');
                        }
                        
                        $data['ys_view_count'] = $this->post('ys_view_count','') ;
                        if(empty($data['ys_view_count'])){
                            $data['ys_view_count'] = 0;
                        }                       
                        
                        if($id)
			{       $data['update_time'] =  date("Y-m-d H:i:s");
				$model->modify($data, $id);
                                
                                $relationModel = new RelationModel();
                                $tagsList = $relationModel->getList(['relation_knowledge_id'=>$id,'relation_status'=> 1]);
                                
                                //var_dump($tagsList);die();
                                $info['relation_status'] = 0;
                                $relationModel->tractionModify($id, $tagsList,  $info['relation_status']);


                                $tag1Ids = !empty($_POST['tag1_id']) ? $_POST['tag1_id'] : "";
                                $tag2Ids = !empty($_POST['tag2_id']) ? $_POST['tag2_id'] : "";

//                                $tag1Ids = $this->post('tag1_id','');
//                                var_dump($tag1Ids);die();
                                                               
                                if(empty($tag1Ids)){
                                        $tag1Ids=array();                        
                                    }elseif(empty ($tag2Ids)){
                                        $tag2Ids=array(); 
                                    }
                    
                                $data['tag_id'] = array_merge($tag1Ids, $tag2Ids);
                                
                                if(is_array( $data['tag_id'] ))
                                 {  
                                     $relationModel = new RelationModel();
                                     $relation_satus = 1;                            
                                     $relationModel ->tractionInsert($id, $data['tag_id'], $relation_satus);                                       
                                    
                                 }else{
                                     $relationModel = new RelationModel();
                                     $info['relation_knowledge_id'] = $primaryId;
                                     $info['relation_tag_id'] = $data['tag_id'];
                                     $info['relation_satus'] = 1;
                                     $relationModel->add($info);
                                 }                               
			}
			else
			{       //var_dump($data);die();
				$data['create_time'] = date("Y-m-d H:i:s");
				$primaryId = $model->add($data);
                                
                                $tag1Ids = !empty($_POST['tag1_id']) ? $_POST['tag1_id'] : "";
                                $tag2Ids = !empty($_POST['tag2_id']) ? $_POST['tag2_id'] : "";
//                                $tag1Ids = $_POST['tag1_id'];
//                                $tag2Ids = $_POST['tag2_id'];
                                //var_dump($tag1Ids); var_dump($tag2Ids);die();
                                
                                
                                if(empty($tag1Ids)){
                                        $tag1Ids=array();                        
                                    }elseif(empty ($tag2Ids)){
                                        $tag2Ids=array(); 
                                    }
                    
                                $data['tag_id'] = array_merge($tag1Ids, $tag2Ids);
                                
                                if(is_array( $data['tag_id'] ))
                                 {  
                                     $relationModel = new RelationModel();
                                     $relation_satus = 1;
                                     $relationModel ->tractionInsert($primaryId, $data['tag_id'], $relation_satus);
                                 }else{
                                     $relationModel = new RelationModel();
                                     $info['relation_knowledge_id'] = $primaryId;
                                     $info['relation_tag_id'] = $data['tag_id'];
                                     $info['relation_satus'] = 1;
                                     $relationModel->add($info);
                                 }
			}
			$output['msg'] = '操作成功!';
                        $output['url'] = '/knowledge/index?type='.$data['type'];
                        $this->forward($output);
                }
                        else
                        {
			$output['msg'] = '非法请求!';
                        }
		
                                                             
                } 
                
    public function actionEdit()
    {                 
                        $id = $this->get('id');
                        $type = $this->get('type');
                        $teacherModel = new TeacherModel();
                        $teachers = $teacherModel->getList(['teacher_status'=>1]);
                        
                        $knowledgeModel = new KnowledgeModel();
                        $knowledges = $knowledgeModel->getRowById($id);
                        
                       
                        $tagModel = new \bc\model\knowledge\KnowledgecategorytagModel();
                        $tagModel ->autoId = 'category_id';
                        $tags1List = $tagModel->getFTagList(['category_id' => $knowledges['category_id'] , 'bc_knowledge_tag.tag_type'=> 1,'category_tag_status' => 1,'bc_knowledge_tag.tag_status'=> 1]);
                        $tags2List = $tagModel->getFTagList(['category_id' => $knowledges['category_id'] , 'bc_knowledge_tag.tag_type'=> 2,'category_tag_status' => 1,'bc_knowledge_tag.tag_status'=> 1]);
                        
                        $categoryModel = new CategoryModel();
                        $categorys = $categoryModel->getList(['parent_id' => 0, 'cate_status' => 1]);

                        //var_dump($tag);die();
                        $relationModel = new RelationModel();
                        //$tagModel ->autoId = 'category_id';
                        $tags1 = $relationModel->getTagList(['relation_knowledge_id' => $id ,'bc_knowledge_tag.tag_type' => 1,'relation_status' => 1,'bc_knowledge_tag.tag_status' => 1]);
                        $tags2 = $relationModel->getTagList(['relation_knowledge_id' => $id ,'bc_knowledge_tag.tag_type' => 2,'relation_status' => 1,'bc_knowledge_tag.tag_status' => 1]);                        
                        
                        $view['knowledges'] = $knowledges;
                        $view['teachers'] = $teachers;
                        $view['categorys'] = $categorys;
                        $view['rows1'] = $tags1List;
                        $view['rows2'] = $tags2List;
                        $view['tags1'] = $tags1;
                        $view['tags2'] = $tags2;
                        $view['type'] = $type;
                        return $this->render('edit',$view);
        
    }
    public function actionDelete()
    {
                       $id = $this->get('id');
                       $type = $this->get('type');
                       $model = new KnowledgeModel();
                       $data['status'] = 0;
                       $model ->modify($data, $id);
                       
                       $output['msg'] = '操作成功!';
                       $output['url'] = '/knowledge/index?type='.$type;
                       $this->forward($output);
               
    }
    
    public function actionStatistics()
    {                     
                        $params = '1 = 1';
                        $id = $this->get('id');
                        //$type = $this->get('type');
	                $params.= " and bc_knowledge_statistics.knowledge_id= {$id}"; 
                        
                        $start_time_str = $this->get('start_time', '');
                        $end_time_str = $this->get('end_time', '');
                        
                        $start_time = $start_time_str ? strtotime($start_time_str) : '';
                        $end_time = $end_time_str ? strtotime($end_time_str) : '';                       
                       
                        if($start_time != '')
                        {   
                            $start_time-=60*60*24;
                            $params.= " and UNIX_TIMESTAMP(bc_knowledge_statistics.start_time) >= {$start_time}";
                        }

                        if($end_time != '')
                        {
                            $end_time+=60*60*24;
                            $params.= " and UNIX_TIMESTAMP(bc_knowledge_statistics.end_time) <= {$end_time}";
                        }
                        
                        $statisticsModel = new StatisticsModel();
                                             
                        $page = $this->get('page', 1);

                        //$model->sort = 'start_time Desc';
                        $list = $statisticsModel->getStatisticsList($params, $page, 10);
                        
                        //var_dump($list);die();

                        $total = $statisticsModel->getTotal($params);

                        $pagination = new Page($total, 10);

                        $view['list'] = $list;
                        $view['pagination'] = $pagination;

                        return $this->render('sort',$view);
    }
    /*
    * ajax拼接分类标签框
    */
    public function  actionAjaxtags()
    {           
             
                $category_id = (int)$this->post('category_id');
                //var_dump($category_id);die();
                if($category_id){
                    $model = new \bc\model\knowledge\KnowledgecategorytagModel();
                    $tags2 = $model->getFTagList(['category_id' => $category_id , 'bc_knowledge_tag.tag_type' => 1,'bc_knowledge_tag.tag_status'=>1,'bc_knowledge_category_tag.category_tag_status'=>1]); 
                }
                
                echo json_encode($tags2);
		exit;
    }
    /*
     * ajax拼接普通标签框
     */
    public function actionAjaxtag()
	{
		$category_id = (int)$this->post('category_id');
		
		 if($category_id){
                    $model = new \bc\model\knowledge\KnowledgecategorytagModel();
                    $tags1 = $model->getFTagList(['category_id' => $category_id , 'bc_knowledge_tag.tag_type' => 2,'bc_knowledge_tag.tag_status'=>1,'bc_knowledge_category_tag.category_tag_status'=>1]); 
                }
		
		echo json_encode($tags1);
		exit;
	}
     /*
     * ajax获取讲师副标题及图片
     */
    public function actionAjaxcontent()
	{
		$teacher_id = (int)$this->post('teacher_id');		
		
		if($teacher_id >= 0)
		{
			$teacherModel = new TeacherModel();
			$content = $teacherModel->getList(['teacher_id' => $teacher_id,'teacher_status' => 1]);
		}
				
		echo json_encode($content);
		exit;
	}
    private function getUploadConfig()
	{
		//上传文件目录
		$path = UPLOAD_PATH . 'upload/';
		//上传配置
		$config = array(
				"savePath" => $path ,             //存储文件夹
				"maxSize" => 100000 ,                   //允许的文件最大尺寸，单位KB
				"allowFiles" => array( ".gif" , ".png" , ".jpg" , ".jpeg" , ".bmp" )  //允许的文件格式
		);
			
		//背景保存在临时目录中
		$config[ "savePath" ] = $path;
		return $config;
	}
}



